import request, { RequestOptionsInit } from 'umi-request';
import { message } from 'antd';
import { history } from 'umi';

// declare type Methods =
//   | 'GET'
//   | 'OPTIONS'
//   | 'HEAD'
//   | 'POST'
//   | 'PUT'
//   | 'DELETE'
//   | 'TRACE'
//   | 'CONNECT';
// declare type Headers = { [key: string]: string };
// declare type Datas = { method: Methods; [key: string]: any };

// encodeURIComponent()
const urlList = { env: 'http://localhost:3000' };
request.interceptors.request.use((url, options) => {
  // console.log(),'11')
  return {
    // url: `/api${url}`,
    url: `${urlList.env}${url}`,
    options: {
      ...options,
      interceptors: true,
      header: {
        'Content-Type': 'application/json;charset=utf-8',
        // 'env': 'mock',
      },
    }, // 定义请求头
  };
});

// request interceptor, change url or options.
// request.interceptors.request.use((url, options) => {
//     return {
//       url: `${url}&interceptors=yes`,
//       options: { ...options, interceptors: true },
//     };
//   });

//   // Same as the last one
//   request.interceptors.request.use(
//     (url, options) => {
//       return {
//         url: `${url}&interceptors=yes`,
//         options: { ...options, interceptors: true },
//       };
//     },
//     { global: true }
//   );

// response interceptor, chagne response
//   request.interceptors.response.use((response, options) => {
//     response.headers.append('interceptors', 'yes yo');
//     return response;
//   });

// handling error in response interceptor 状态吗
request.interceptors.response.use((response) => {
  console.log(response, 'response');
  if (response.status >= 400) {
    message.error(response.statusText);
  } else if (response.status === 301) {
    history.push('/login');
  }
  return response;
});

// clone response in response interceptor
//   request.interceptors.response.use(async response => {
//     const data = await response.clone().json();
//     if (data && data.NOT_LOGIN) {
//       location.href = '登录url';
//     }
//     return response;
//   });

export default request;
